package com.toocms.jinjuhang.ui.mine.management_system.withdraw

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.BankItemData
import com.toocms.jinjuhang.data.center.BankListData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger

class WithdrawModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {

    var selectedBank: BankItemData? = null
    val sumObservableField = ObservableField<String>()
    val balanceObservableField by lazy {
        val content = bundle?.getString(Constants.BundleKey.KEY_BALANCE) ?: "00"
        ObservableField(content)
    }

    val items = ObservableArrayList<WithdrawAccountItemModel>()
    val itemBinding = ItemBinding.of<WithdrawAccountItemModel>(
        BR.withdrawAccountItemModel, R.layout.item_withdraw_account
    )

    val allRollOutClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        sumObservableField.set(balanceObservableField.get())
    })

    val confirmClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        if (null == selectedBank || selectedBank?.bank_id.isNullOrEmpty()) {
            showToast("请选择银行卡")
            return@BindingAction
        }
        withdraw( selectedBank?.bank_id ?: "",sumObservableField.get() ?: "")
    })

    init {
        requestData(
            Urls.Center.BANK_LIST,
            mapOf(Pair("member_id", UserRepository.user.member_id)),
            resultClass = BankListData::class.java,
            result = {
                items.clear()
                it.list?.forEach {
                    items += WithdrawAccountItemModel(this@WithdrawModel, ObservableField(it))
                }
            })
    }

    private fun withdraw(bankId: String, amounts: String) {
        val param = mutableMapOf<String, String?>()
        param["member_id"] = UserRepository.user.member_id
        param["bank_id"] = bankId
        param["amounts"] = amounts
        requestData(Urls.Center.WITHDRAW, param, resultClass = String::class.java, result = {
            showToast(it)
            Messenger.getDefault()
                .sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_BALANCE)
            finishFragment()
        })
    }

}